package com.sentiment.entrance;

import org.apache.log4j.Logger;
import org.bson.Document;
import org.json.JSONObject;

import com.sentiment.algorithm.PageInOut;
import com.sentiment.config.Config;
import com.sentiment.crawler.BaiduCrawler;
import com.sentiment.db.TextDB;
import com.sentiment.obj.Text;
import com.sentiment.port.EnterTo;

public class EnterToLsh implements EnterTo {
	private static Text tx;
	private static BaiduCrawler bdsrch;
	private Logger logger = Config.getLogger(this.getClass());

	@Override
	public JSONObject getJson(String statusStr, int progress) {
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("progress", progress);
		jsonObj.put("statusStr", statusStr);
		return jsonObj;
	}

	@Override
	public String stepOne(String srcId) {
		TextDB tdb = new TextDB();
		tx = tdb.findDataByKeyAndVal("id", srcId);
		// 结束Mongodb线程
		tdb.DBClose();
		return "-----创建数据库连接对象并读取到原文完成，正在搜索引擎爬取页面中-----";
	}

	@Override
	public String stepTwo() {
		// 将切割好的句子送入baidu爬虫
		bdsrch = new BaiduCrawler(Config.crawlerDataPath, tx.getId());
		// 获取到原文的第一段第一句
		String first = tx.getContent(1, 1);
		logger.info("search keyword : " + first);
		bdsrch.getSearch(first);
		return "-----将原文内容置于搜索引擎并爬取页面完成，正在解析html页面中-----";
	}

	@Override
	public String stepThree() {
		bdsrch.createRalationMap();
		return "-----创建文章关系图完成，正在Lsh处理-----";
	}

	@Override
	public String stepFour() {
		bdsrch.parserAllHtml();
		return "-----解析html页面完成，正在创建文章关系图-----";
	}

	@Override
	public String stepFive() {
		// Lsh处理Src和Crawl的文本文件
		PageInOut pio = new PageInOut();
		pio.LshPageFromDB(tx.getId());
		return "-----Lsh处理完成，点击下方按钮显示结果页面-----";
	}

	private static String getText(Text tx) {
		String result = "";
		Document doc = tx.getContent();
		int paraAmount = tx.getParaAmount();
		for (int i = 1; i <= paraAmount; i++) {
			Document para = (Document) doc.get(Integer.toString(i));
			int stnAmount = para.getInteger("stnAmount");
			for (int j = 1; j <= stnAmount; j++) {
				result += ((Document) para.get(Integer.toString(j))).getString("text");
			}
		}
		return result;
	}
}
